<template>
  <div id="webdav">
    <el-row>
      <el-col :span="24" style="margin-top:10px;">
        <input type="file" id="fileIni" accept=".*" style="display:none" @change="onFileChange">
        <el-button @click="onUploadClick">{{$t('message.upload')}}</el-button>
        <el-button @click="createFolderVisible=true">{{$t('message.file.createFolder')}}</el-button>
        <el-button @click="backToParentFolder(false)">{{$t('message.file.backToPre')}}</el-button>
        <el-progress  :stroke-width="10" :percentage="uploadPercent" style="width:100%;" v-show="isShowUploadProgres"></el-progress>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table :data="tableData" @row-dblclick='onClickTableRow' highlight-current-row>
          <el-table-column :label="$t('message.name')" min-width="140px;" class="tb-col">
            <template slot-scope="scope">
              <i v-if="scope.row.type=='directory'" class="iconfont el-icon-erp-folder" style="font-size:18px;"></i>
              <i :class="showClass(scope.row.name)" style="font-size:18px;"></i>
              <span>{{scope.row.name}}</span>             
            </template>
          </el-table-column>
          <el-table-column :label="$t('message.type')" min-width="140px;">
            <template slot-scope="scope">
              <span v-if="scope.row.type=='directory'">{{$t('message.file.folder')}}</span>
              <span v-if="scope.row.type=='file'">{{$t('message.file.file')}}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('message.file.motifiTime')"
            prop="mtime">
          </el-table-column>
          <el-table-column :label="$t('message.medias.operation')" min-width="140px;">
            <template slot-scope="scope">
              <el-button size="mini" v-show="scope.row.type!='directory'" @click="downloadFile(scope.row)" >{{$t('message.file.dowload')}}</el-button>  
              <el-button size="mini" @click="delFileOrFolder(scope.row)">{{$t('message.file.delete')}}</el-button>  
              <el-button size="mini" v-show="scope.row.type!='directory'" @click="onCpClick(scope.row)">{{$t('message.file.copyTo')}}</el-button>  
              <el-button size="mini" v-show="scope.row.type!='directory'" @click="onMoveClick(scope.row)">{{$t('message.file.moveTo')}}</el-button> 
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>   
    <!-- 创建文件夹弹窗 -->
    <el-dialog :title="$t('message.file.createFolder')" :visible.sync="createFolderVisible" width="660px">
      <el-form  label-width="120px" ref="audio"  size="mini">     
        <el-form-item :label="$t('message.name')">        
          <el-input v-model="folderName"></el-input>
        </el-form-item>    
        <el-form-item >
          <el-button  @click="onCreatFolder">{{$t('message.ok')}}</el-button>
          <el-button @click="createFolderVisible = false">{{$t('message.cancel')}}</el-button>
        </el-form-item>    
      </el-form>    
    </el-dialog>   
    <!-- 移动文件弹窗 -->
    <el-dialog :title="$t('message.file.selectFolder')" :visible.sync="moveItemVisible" width="660px">
      <el-button @click="backToParentFolder(true)" >{{$t('message.file.backToPre')}}</el-button>
      <el-table :data="moveToFolderData" @row-dblclick='onDbClickMoveTableRow' @row-click="onClickMoveTableRow" highlight-current-row>
        <el-table-column :label="$t('message.name')" min-width="140px;">
          <template slot-scope="scope" >
            <i v-if="scope.row.type=='directory'" class="iconfont el-icon-erp-folder" style="font-size:18px;"></i>
            <i :class="showClass(scope.row.name)" style="font-size:18px;"></i>
            <span>{{scope.row.name}}</span>             
          </template>
        </el-table-column>
      </el-table>
     <el-button @click="onMoveOrCp">{{$t('message.ok')}}</el-button>
     <el-button @click="moveItemVisible = false">{{$t('message.cancel')}}</el-button>
    </el-dialog>      
  </div>
</template>

<script>
import { WebDAV } from "@/libs/webdav.js";
import { getHostName, api } from "@/libs/api.js";
import { mapState, mapActions } from "vuex";
import { downloadFile } from "@/libs/utils";
var base64 = require('base-64');
var utf8 = require('utf8');

import axios from "axios";

export default {
  created() {
    this.getDav();
    this.listenKepyDown();
  },
  computed: {
    ...mapState(["system"]),
  },
  data() {
    return {
      uploadPercent: 0,
      isShowUploadProgres: false,
      moveOrCpType: '',
      toMoveName: '',
      toMoveFolder: '',
      curFolder: '',
      moveItemVisible: false,
      createFolderVisible: false,
      defaulturl: "http://" + getHostName() + ":8080/_default/",
      url: "http://" + getHostName() + ":8080/_default/",
      moveToFolderUrl: "http://" + getHostName() + ":8080/_default/",
      folderName: "",
      tableData: [],
      moveToFolderData: [],
      nodes: [],
      defaultProps: {
        children: "children",
        label: "name"
      }
    };
  },
  methods: {
    listenKepyDown(){
      document.onkeydown = function onkeydown(e) {
        var ev = e || window.event;//获取event对象          
        if(ev.keyCode == 8 ){  
          this.backToParentFolder(this.moveItemVisible);    
        }
      }.bind(this) 
    },
    getDav() {
      var fs = new WebDAV.Fs("http://192.168.21.165:8080/_default");
      axios.get(this.url).then(res => {
        this.nodes = res.data;
        this.tableData = res.data;
        this.moveToFolderData = res.data;
        console.log("data:", res.data);
      });
    },
    onClickTableRow(row) {
      this.getListByName(row, false);
    },
    onDbClickMoveTableRow(row) {      
      this.getListByName(row, true);
    },
    onClickMoveTableRow(row){
      this.toMoveFolder = row.name + '/';
    },
    getListByName(row, isMoveOrCp) {
      if (row.type == "directory") {
        if(isMoveOrCp){
          axios.get(this.moveToFolderUrl + row.name + "/").then(res => {
            this.moveToFolderUrl += row.name + "/";
            this.moveToFolderData = res.data;
          });
        } else{
          axios.get(this.url + row.name + "/").then(res => {
            this.url += row.name + "/";
            this.tableData = res.data;
            console.log("data:", res.data);
          });
        }
        
      }
    },
    backToParentFolder(isMoveOrCp) {
      if(isMoveOrCp){
        var urlSplitArr = this.moveToFolderUrl.split("/");
        if (urlSplitArr.length > 4) {
          urlSplitArr.splice(urlSplitArr.length - 1, 1);
          if (urlSplitArr.length > 4) {
            urlSplitArr.splice(urlSplitArr.length - 1, 1);
          }
        }
        var url = urlSplitArr.join("/") + "/";
        axios.get(url).then(res => {
          this.moveToFolderUrl = url;
          this.moveToFolderData = res.data;
        });
      }else{
        var urlSplitArr = this.url.split("/");
        if (urlSplitArr.length > 4) {
          urlSplitArr.splice(urlSplitArr.length - 1, 1);
          if (urlSplitArr.length > 4) {
            urlSplitArr.splice(urlSplitArr.length - 1, 1);
          }
        }
        var url = urlSplitArr.join("/") + "/";
        axios.get(url).then(res => {
          this.url = url;
          this.tableData = res.data;
          console.log("data:", res.data);
        });
      }
      
    },
    delFileOrFolder(row) {
      var url = this.url + row.name;
      if(row.type == 'directory'){
        url += '/';
      }
      axios
        .delete(url, {
          headers: { Authorization: "Bearer " + this.system.JWT }
        })
        .then(res => {
          if(res.status.toString().startsWith('2')){
            this.getDav();
            this.notification('Success', '');
          } else{
            this.notification('Error', res.status)
          }
        }).catch((err) => {   
        this.notification('Error', '');
        this.getDav();
      });
    },
    onUploadClick() {
      var upload = document.getElementById("fileIni");
      upload.click();
    },
    onFileChange(e) {
      var file = document.getElementById("fileIni").files[0];
      axios
        .put(this.url + file.name, file, {
          headers: { Authorization: "Bearer " + this.system.JWT },
          onUploadProgress: this.onUploadProgress
        })
        .then(res => {
          if(res.status.toString().startsWith('2')){
            this.uploadPercent = 0;
            this.isShowUploadProgres = false;
            this.getDav();
            this.notification('Success', '');
          } else{
            this.notification('Error', res.status)
          }
        });
    },
    onUploadProgress(evt){
      if (evt && evt.lengthComputable) {
        console.log('progress:', 100 * evt.loaded / evt.total)
        this.isShowUploadProgres = true;
        this.uploadPercent = parseInt(100 * evt.loaded / evt.total) 
      }
    },
    onCreatFolder() {
      axios({
        method: "MKCOL",
        url: this.url + this.folderName + "/",
        headers: {
          Authorization: "Bearer " + this.system.JWT,
          "Content-Type": "text/xml"
        }
      }).then(res => {
        if(res.status.toString().startsWith('2')){
          this.notification("Success", "");
        } else{
          this.notification('Error', res.status);
        }
        this.createFolderVisible = false;
        this.getDav();
      }).catch((err) => {    
        this.notification('Error', '');
        this.getDav();
      });
    },
    prevenUp(e) {
      //js阻止事件冒泡
      e.cancelBubble = true;
      e.stopPropagation();
    },
    onMoveClick(row){
      this.moveOrCpType = 'MOVE';
      this.toMoveFolder = '';
      this.toMoveName = row.name;
      this.moveItemVisible = true;
      this.getDefaultData();      
    },
    onCpClick(row){
      this.moveOrCpType = 'COPY';
      this.toMoveFolder = '';
      this.toMoveName = row.name;
      this.moveItemVisible = true;
      this.getDefaultData();      
    },
    getDefaultData(){
      axios.get(this.defaulturl).then(res => {
        this.moveToFolderUrl = this.defaulturl;
        this.moveToFolderData = res.data;
      });
    },
    onMoveOrCp(row, type) {      
      if(!this.toMoveFolder){
        return;
      }
      var index = this.toMoveName.lastIndexOf('.');
      var fileName = this.toMoveName.substr(0, index);//文件名
      var subfix = this.toMoveName.substr(index);//文件后缀
      var base64Url = encodeURI(fileName);//base64转码
      var url = this.url + base64Url + subfix;//完整路径

      var xhr = new XMLHttpRequest();
      xhr.open(this.moveOrCpType, url, true);
      xhr.onload = function(res) {
      };
      xhr.onerror = (err) =>{
        this.notification('Error', '');
        this.moveItemVisible = false;
        this.getDav();
      };
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          //判断http的交互是否成功
          if (xhr.status.toString().startsWith('2')) {
            var responseText = xhr.responseText;
            this.notification("Success", "");
          } else{
            this.notification('Error', res.status);
          }
          this.moveItemVisible = false;
          this.getDav();
        }
      }.bind(this);
      xhr.setRequestHeader('Authorization', "Bearer " + this.system.JWT);
      xhr.setRequestHeader('Destination', this.moveToFolderUrl + this.toMoveFolder + base64Url + subfix);
      xhr.send(null); 
    },
    downloadFile(row){
      downloadFile(this.url + row.name, row.name);
    },
    showClass(type){      
      if(type.toUpperCase().includes('.TAR') || type.toUpperCase().includes('.IMG') || type.toUpperCase().includes('.RAR') || type.toUpperCase().includes('.ZIP') || type.toUpperCase().includes('.GZ') || type.toUpperCase().includes('.7Z')){
        return 'iconfont el-icon-erp-zip';
      } else if(type.toUpperCase().includes('.JP') || type.toUpperCase().includes('.PNG') || type.toUpperCase().includes('.BMP') || type.toUpperCase().includes('.GIF')){
        return 'iconfont el-icon-erp-picture';
      } else if(type.toUpperCase().includes('.MP3') || type.toUpperCase().includes('.AAC') || type.toUpperCase().includes('.WAV') || type.toUpperCase().includes('.MWA')){
        return 'iconfont el-icon-erp-yinpin';
      } else if(type.toUpperCase().includes('.MP4') || type.toUpperCase().includes('.3GP') || type.toUpperCase().includes('.AUI') || type.toUpperCase().includes('.MOV') || type.toUpperCase().includes('.ASF')){
        return 'iconfont el-icon-erp-ai-video';
      } else if(type.toUpperCase().includes('.TXT')){
        return 'iconfont el-icon-erp-txt';
      } else if(type.toUpperCase().includes('.DOC')){
        return 'iconfont el-icon-erp-word';
      } else if(type.toUpperCase().includes('.XL')){
        return 'iconfont el-icon-erp-excel';
      } else if(type.toUpperCase().includes('.EXE')){
        return 'iconfont el-icon-erp-EXE';
      } else{
        return '';
      }
    }
  }
};
</script>

